package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.connection.stream.Consumer;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.connection.stream.StreamOffset;
import org.springframework.data.redis.connection.stream.StreamReadOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> STOCK_SCRIPT;

    static {
        STOCK_SCRIPT = new DefaultRedisScript<>();
        STOCK_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        STOCK_SCRIPT.setResultType(Long.class);
    }

    //在类初始化完成以后就立即执行该方法
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }


    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * VoucherOrderServiceImpl类的代理对象
     * 将代理对象的作用域进行提升，方面子线程取用
     */
    private IVoucherOrderService proxy;




    String queueName = "stream.orders";
    private final String groupName = "g1";
    private volatile boolean groupInitialized = false;

    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            // 在开始处理前确保消费者组存在
            ensureConsumerGroup();

            while (true) {
                try {
                    //1. 获取队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> records = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            //ReadOffset.lastConsumed()底层就是 '>'
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    //2. 判断消息是否获取成功
                    if (records == null || records.isEmpty()) {
                        continue;
                    }
                    //3. 消息获取成功之后，我们需要将其转为对象
                    MapRecord<String, Object, Object> record = records.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    //4. 获取成功，执行下单逻辑，将数据保存到数据库中
                    handleVoucherOrder(voucherOrder);
                    //5. 手动ACK，SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    // 检查是否是消费者组不存在的错误
                    if (e.getMessage() != null && e.getMessage().contains("NOGROUP")) {
                        log.warn("消费者组不存在，重新创建: {}", e.getMessage());
                        groupInitialized = false; // 重置标志
                        ensureConsumerGroup(); // 重新创建消费者组
                        continue; // 跳过本次循环，重新尝试
                    }
                    log.error("订单处理异常", e);
                    //订单异常的处理方式我们封装成一个函数，避免代码太臃肿
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                //1. 获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders 0
                List<MapRecord<String, Object, Object>> records = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(queueName, ReadOffset.from("0")));
                //2. 判断pending-list中是否有未处理消息
                if (records == null || records.isEmpty()) {
                    //如果没有就说明没有异常消息，直接结束循环
                    break;
                }
                //3. 消息获取成功之后，我们需要将其转为对象
                MapRecord<String, Object, Object> record = records.get(0);
                Map<Object, Object> values = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                //4. 获取成功，执行下单逻辑，将数据保存到数据库中
                handleVoucherOrder(voucherOrder);
                //5. 手动ACK，SACK stream.orders g1 id
                stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
            } catch (Exception e) {
                // 同样处理消费者组不存在的情况
                if (e.getMessage() != null && e.getMessage().contains("NOGROUP")) {
                    log.warn("处理pending-list时消费者组不存在，重新创建");
                    groupInitialized = false;
                    ensureConsumerGroup();
                    continue;
                }
                log.info("处理pending-list异常");
                //如果怕异常多次出现，可以在这里休眠一会儿
                try {
                    Thread.sleep(50);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    // 使用 Lua 脚本确保消费者组存在
    private void ensureConsumerGroup() {
        if (!groupInitialized) {
            synchronized (this) {
                if (!groupInitialized) {
                    try {
                        // 使用 Lua 脚本确保原子性操作
                        String luaScript =
                                "local groups = redis.call('XINFO', 'GROUPS', KEYS[1]) " +
                                        "for i = 1, #groups do " +
                                        "    if groups[i][2] == ARGV[1] then " +
                                        "        return 'EXISTS' " +
                                        "    end " +
                                        "end " +
                                        "redis.call('XGROUP', 'CREATE', KEYS[1], ARGV[1], '0', 'MKSTREAM') " +
                                        "return 'CREATED'";

                        String result = stringRedisTemplate.execute((RedisConnection connection) -> {
                            Object res = connection.eval(luaScript.getBytes(), ReturnType.VALUE, 1,
                                    queueName.getBytes(), groupName.getBytes());
                            // 处理字节数组转字符串
                            if (res instanceof byte[]) {
                                return new String((byte[]) res);
                            }
                            return res != null ? res.toString() : "UNKNOWN";
                        });

                        log.info("消费者组状态: {}", result);
                        groupInitialized = true;
                    } catch (Exception e) {
                        log.error("创建消费者组失败", e);
                        groupInitialized = true; // 避免无限重试
                    }
                }
            }
        }
    }

    /*//阻塞队列
  private static final BlockingQueue<VoucherOrder> oredrTasks = new ArrayBlockingQueue<>(1024 * 1024);

  //线程任务
  private class VoucherOrderTask implements Runnable{
      @Override
      public void run() {
          while (true){
              //从阻塞队列中获取用户信息，并且创建订单
              try {
                  VoucherOrder voucherOrder = oredrTasks.take();
                  //创建订单
                  handleVoucherOrder(voucherOrder);
              } catch (InterruptedException e) {
                  log.error("订单处理异常",e);
              }

          }
      }*/
        //创建订单
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //5.创建订单(加锁)
            Long userId = voucherOrder.getId();
            //6.创建锁对象
            RLock lock = redissonClient.getLock("lock:order:key:" + userId);
            //7.获取锁
            boolean isLock = lock.tryLock();
            //8.判断获取锁成功
            if (!isLock) {
                // 索取锁失败，重试或者直接抛异常（这个业务是一人一单，所以直接返回失败信息）
                log.error("一人只能下一单");
                return;
            }
            try {
                // 创建订单（使用代理对象调用，是为了确保事务生效）
                proxy.createVoucherOrder(voucherOrder);
            } finally {
                lock.unlock();
            }
        }

        //一人一单业务逻辑(提取出来方便加锁)
        @Transactional
        public void createVoucherOrder(VoucherOrder voucherOrder) {
            //5一人一单逻辑
            //5.1用户id
            Long userId = voucherOrder.getUserId();
            int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count > 0) {
                log.error("用户已经购买过一次");
                return;
            }
            //5.扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock=stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0)
                    .update();
            if (!success) {
                log.error("库存不足");
                return;

            }
            //创建订单
            save(voucherOrder);
        }

        /**
         * 秒杀优惠券购买
         */

        @Override
        public Result seckillVoucher(Long voucherId) {
            //获取用户id
            Long userId = UserHolder.getUser().getId();
            //获取到订单id
            long orderId = redisIdWorker.netxId("order");
            //1.执行lua脚本
            Long result = stringRedisTemplate.execute(
                    STOCK_SCRIPT,
                    Collections.emptyList(),
                    voucherId.toString(), userId.toString(), String.valueOf(orderId)
            );
            //2.判断结果是否为0
            int r = result.intValue();
            if (r != 0) {
                //2.1.结果不为0，代表没有购买资格
                return Result.fail(r == 1 ? "库存不足" : "不可重复下单");
            }
            //获取代理对象
            proxy = (IVoucherOrderService) AopContext.currentProxy();
            //返回订单id
            return Result.ok(orderId);
        }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始");
//        }
//        //3.判断秒杀是否结束
//        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束");
//        }
//        //4.判断库存是否充足
//        if(voucher.getStock() < 1 ){
//            return Result.fail("库存不足!");
//        }
//        //5.创建订单(加锁)
//        Long userId = UserHolder.getUser().getId();
//        //6.创建锁对象
//        //1️⃣SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order" + userId);
//        RLock lock = redissonClient.getLock("lock:order:key:" + userId);
//        //7.获取锁
//        //1️⃣boolean isLock = lock.tryLock(1200);
//        boolean isLock = lock.tryLock();
//        //8.判断获取锁成功
//        if (!isLock) {
//            //获取锁不成功，返回失败(一人一单)
//            return Result.fail("请勿重复下单");
//        }
//        try {
//            //获取代理对象(事务)
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//    }

    }

